package com.jjz.id.common.utils;

import com.jjz.id.model.UserInfo;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;

/**
 * @author ZJL
 * @create 2025-05-27-15:52
 */

public class SecurityUtils {
    public static final String ACCESS_TOKEN_REQUEST_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";


    public static void throwError(String errorCode, String parameterName, String errorUri) {
        OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
        throw new OAuth2AuthenticationException(error);
    }

    public static String getCurrentUser() {
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }

    public static UserInfo getCurrentUserInfo() {
        return (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public static void loadUser(String user) {
        SimpleAuthentication simpleAuthentication = new SimpleAuthentication(user);
        SecurityContextHolder.getContext().setAuthentication(simpleAuthentication);
    }

    public static void clearUser() {
        SecurityContextHolder.clearContext();
    }
}
